package cn.kgc.base.controller;

import cn.hutool.core.util.RandomUtil;
import cn.kgc.commons.constant.HttpExceptionCodeEnum;
import cn.kgc.commons.constant.SystemConstant;
import cn.kgc.commons.exception.HttpException;
import cn.kgc.commons.util.RedisUtil;
import cn.kgc.commons.util.SendPhoneMessage;
import cn.kgc.commons.vo.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.net.ServerSocket;
import java.util.concurrent.TimeUnit;

/**
 * <p>发送验证码的控制器</p>
 *
 * @author 卢传琪
 */
@RestController
@RequestMapping("/code")
@Api(tags = "获得验证码的控制器")
@Slf4j
@ConditionalOnClass(ResponseBodyAdvice.class)
public class SendCodeController {
    @Resource
    private RedisUtil redisUtil;

    @GetMapping("/send")
    @ApiOperation(value = "获得验证码",httpMethod = "GET",produces = "application/json;charset=utf-8")
    @ApiImplicitParam(name = "phone",value = "手机号",paramType = "query",dataType = "string")
    public Result code(@RequestParam("phone") String phone, HttpServletRequest request)throws Exception{
        String key=SystemConstant.REGISTER_PHONE_CODE+phone;
        if (redisUtil.hasKey(key)){
            throw new HttpException(HttpExceptionCodeEnum.PHONE_CODE_REPEAT.getCode(), HttpStatus.INTERNAL_SERVER_ERROR.value());
        }
        //产生随机数，验证码
        int code= RandomUtil.randomInt(100000,999999);
        //将验证码保存到redis中
        redisUtil.set(key,code, SystemConstant.PHONE_CODE_TIMEOUT, TimeUnit.MINUTES);
        log.info("验证码为：{}",code);
        return Result.success(code,request.getRequestURI().toString());
    }
}
